package com.liurui.demo.contoller;

import com.liurui.demo.dao.DepartmentDao;
import com.liurui.demo.dao.EmployeeDao;
import com.liurui.demo.mapper.DepartmentMapper;
import com.liurui.demo.mapper.EmployeeMapper;
import com.liurui.demo.pojo.Department;
import com.liurui.demo.pojo.Employee;
import com.liurui.demo.service.DepartmentService;
import com.liurui.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

//    @Autowired
//    EmployeeMapper employeeMapper;
//    @Autowired
//    DepartmentMapper departmentMapper;

    @Autowired
    DepartmentService departmentService;

    @Autowired
    EmployeeService employeeService;

    @RequestMapping("/emps")
    public String List(Model model){
        Collection<Employee> employees=employeeService.getEmployees();//存储所有员工
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    //get请求走这个添加方法
    @GetMapping("/emp")
    public String toAdd(Model model){
        //查询部门列表
        Collection<Department> departments = departmentService.getDepartments();
        model.addAttribute("depts",departments);
        //跳转到表单页面
        return "emp/add";
    }

    //post请求走这个方法
    @PostMapping("/emp")
    public String add(Employee employee){
//        System.out.println("Insert:"+employee);
//        //设置员工employee的部门department():前端传过来的只有部门id,
//        employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
        employeeService.insert(employee);
        return "redirect:/emps";
    }

    //前往编辑界面
    @GetMapping("/emp/{id}")//接收前端传来的id
    public String toEdit(@PathVariable("id") Integer id,Model model){
        //跟据id查员工,查出原来的数据
        Employee employee=employeeService.getEmployeeById(id);//employee存在id
        model.addAttribute("emp",employee);

        //查询部门列表
        Collection departments=departmentService.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/edit";
    }

    //添加员工
    @PostMapping("/emp/{id}")
    public String edit(Employee employee){
        employeeService.update(employee);
        return "redirect:/emps";
    }

    //跟据id删除员工
    @GetMapping("/delemp/{id}")
    public String delete(@PathVariable("id") Integer id){
        employeeService.deleteEmployeeById(id);
        return "redirect:/emps";
    }
}
